<?php
/**
 * Created by PhpStorm.
 * User: geolo
 * Date: 2018/8/10
 * Time: 9:47
 */
namespace app\modules\mch\models;

use app\models\LiveSetting;

class LiveSettingForm extends Model
{

    public $org_name;
    public $app_name;
    public $client_id;
    public $client_secret;
    public $wechat_app_id; // 小程序id
    public $is_delete;
    public $createtime;
    public $access_token;
    public $app_key;
    public function rules()
    {
        return [
            [['wechat_app_id', 'org_name','app_name','client_id','client_secret'], 'trim'],
            [['wechat_app_id', 'org_name','app_name','client_id','client_secret','app_key'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'wechat_app_id' => '请先申请小程序',
            'app_key'=>'填写App_Key',
            'org_name'=>'填写应用名称',
            'app_name'=>'填写产品名称',
            'client_id'=>'填写client_id',
            'client_secret' => '填写client_secret',
            'app_key'=>'填写app_key',
        ];
    }

    public function save()
    {
        if (!$this->validate())
            return $this->getModelError();
        $model = new LiveSetting();
        $model->attributes = $this->attributes;
        $model->is_delete = $this->is_delete;
        $model->createtime = $this->createtime;
        $model->wechat_app_id = $this->wechat_app_id;
        $model->access_token = $this->access_token;
//        $data = $this->attributes;
//        var_dump($data);
//        var_dump($model);
        $connection = \Yii::$app->db;
        $command = $connection->createCommand('SELECT count(*) as rcount FROM hjmall_live_setting where wechat_app_id='.$this->wechat_app_id.' and is_delete=0');
        $num = $command->queryOne();
        if($num['rcount']<=0) {
            if ($model->save()) {
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                    'store_id'=>$this->wechat_app_id,
                ];
            }
        }else{
            $upd = LiveSetting::findOne(['wechat_app_id'=>$this->wechat_app_id]);
            $upd->app_key = $this->app_key;
            $upd->org_name = $this->org_name;
            $upd->app_name = $this->app_name;
            $upd->client_id = $this->client_id;
            $upd->client_secret = $this->client_secret;
            $upd->access_token = $this->access_token;
//            var_dump($upd);
            if($upd->save()){
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                    'store_id'=>$this->wechat_app_id,
                ];
            }
        }
        return $this->getModelError($upd);
    }

}